<?php

namespace app\api\controller;

use app\api\model\Order;
use app\api\model\PlatformLog;
use app\api\model\Site;
use app\api\model\UserBill;
use app\common\controller\Api;
use EasyWeChat\Factory;
use fast\Random;
use think\App;
use think\facade\Db;
use think\facade\Validate;
use think\facade\Config;
use app\common\library\Ems;
use app\common\library\Sms;
use think\facade\Log;
use think\Model;
use think\Request;

/**
 * 回调接口.
 */
class Notify
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    protected $model;
    protected $platform_model;

    /**
     * 构造方法
     * @access public
     *
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        $this->model = new Order();
        $this->platform_model = new PlatformLog();
    }

    /**
     * 预约下单回调.
     */
    public function orderNotify()
    {
        Log::write('预约下单支付回调逻辑开始' . date('Y-m-d H:i:s', time()));
        $config = Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) use ($app) {
            Log::write($message);
            if ($message['return_code'] == "SUCCESS" && $message["result_code"] == "SUCCESS") {
                $out_trade_no = $message['out_trade_no'];//订单号
                $order = $this->model->where('out_trade_no', $out_trade_no)->find();
                //如果该订单未找到或已支付,返回true
                if (!$order) {
                    return true;
                }
                //更改订单状态
                $upda_data = [
                    'status' => 2,
                    'transaction_id' => $message['transaction_id'], //微信支付订单号
                    'time_end' => strtotime($message['time_end']), //支付完成时间
                    'total_fee' => $message['total_fee'] / 100, //支付金额
                ];
                $res = $this->model->where('out_trade_no', $out_trade_no)->update($upda_data);
                //平台流水
                $platform_log = $this->platform_model->where(
                    ['user_id' => $order['user_id'], 'type' => 1, 'order_id' => $order['id']]
                )->find();
                if (!$platform_log) {
                    $this->platform_model->save(
                        [
                            'user_id' => $order['user_id'],
                            'amount' => $order['all_money'],
                            'type' => 1,
                            'log_note' => '预约下单支付',
                            'createtime' => time(),
                            'order_id' => $order['id']
                        ]
                    );
                }
                Log::write('预约下单支付回调逻辑结束' . date('Y-m-d H:i:s', time()));
                return true;
            }
        });
        return $response->send();
    }


    public function matchNotify()
    {
        $config = Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
//        $message = array(
//            'appid' => 'wxf436cffbaba49829',
//            'bank_type' => 'OTHERS',
//            'cash_fee' => '1',
//            'fee_type' => 'CNY',
//            'is_subscribe' => 'N',
//            'mch_id' => '1626297451',
//            'nonce_str' => '66b043a7177fd',
//            'openid' => 'obaxI5d8vIWZPbNAJ5QGQED3rTqo',
//            'out_trade_no' => 'XD13613790372282',
//            'result_code' => 'SUCCESS',
//            'return_code' => 'SUCCESS',
//            'sign' => 'ACBED99C27B0D319EE5AB54381807ADC',
//            'time_end' => '20240805111451',
//            'total_fee' => '1',
//            'trade_type' => 'JSAPI',
//            'transaction_id' => '4200002345202408058764788880',
//        );
        $response = $app->handlePaidNotify(function ($message, $fail) use ($app) {
        if ($message['return_code'] == "SUCCESS" && $message["result_code"] == "SUCCESS") {
            $out_trade_no = $message['out_trade_no'];//订单号
            $order = Db::name('match_order')->where(['out_trade_no' => $out_trade_no, 'status' => 0])->find();
            //如果该订单未找到或已支付,返回true
            if (!$order) {
                return true;
            }
            //更改订单状态
            $upda_data = [
                'status' => 2,
                'transaction_id' => $message['transaction_id'], //微信支付订单号
                'pay_time' => time(), //支付完成时间
                'pay_money' => $message['total_fee'] / 100, //支付金额
            ];
            Db::name('match_order')->where('out_trade_no', $out_trade_no)->update($upda_data);

            //添加明细
            $res['title'] = $order['title'];
            $res['username'] = $order['username'];
            $res['phone'] = $order['phone'];
            $res['desc'] = $order['desc'];
            $res['match_id'] = $order['match_id'];
            $res['user_id'] = $order['user_id'];
            $res['create_time'] = time();

            Db::name('match_log')->insert($res);
            return true;
        }
        });
        return $response->send();
    }


    public function rechargeVipCardNotify()
    {
        $config = Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) use ($app) {
        if ($message['return_code'] == "SUCCESS" && $message["result_code"] == "SUCCESS") {
            $out_trade_no = $message['out_trade_no'];//订单号
            $order = Db::name('vip_card_order')->where(['out_trade_no' => $out_trade_no, 'status' => 0])->find();
            //如果该订单未找到或已支付,返回true
            if (!$order) {
                return true;
            }
            //更改订单状态
            $upda_data = [
                'status' => 2,
                'transaction_id' => $message['transaction_id'], //微信支付订单号
                'pay_time' => time(), //支付完成时间
                'pay_money' => $message['total_fee'] / 100, //支付金额
            ];
            try {
                $user = Db::name('user')->where(['id' => $order['user_id']])->find();
                Db::startTrans();
                Db::name('vip_card_order')->where('out_trade_no', $out_trade_no)->update($upda_data);
                $vipCard = (new \app\api\model\VipCard())->where(['id' => $order['vip_card_id']])->find();
                $expiresTime = $this->createDay($vipCard['type'], $vipCard['nums']);
                Db::name('user')->where(['id' => $order['user_id']])->update(
                    ['vip_type' => $vipCard['id'], 'expires_time' => $expiresTime]
                );

                $res['user_id'] = $order['user_id'];
                $res['vip_card_id'] = $vipCard['id'];
                $res['type'] = $vipCard['type'];
                $res['price'] = $vipCard['price'];
                $res['expires_time'] = $expiresTime;
                $res['create_time'] = time();
                Db::name('vip_card_log')->insert($res);

                //执行分佣
                $piduser = Db::name('user')->where(['id' => $user['pid']])->find();
                if ($piduser) {
                    $config = (new \app\common\model\Config())->where(['id' => 44])->find();
                    $divider = number_format($order['pay_money'] * $config['value'] / 100, 2);
                    $team_money = $piduser['team_money'] + $divider;
                    $team_total_money = $piduser['team_total_money'] + $divider;
                    Db::name('user')->where(['id' => $user['pid']])->update(
                        ['team_money' => $team_money, 'team_total_money' => $team_total_money]
                    );
                    //添加明细
                    $arr['user_id'] = $order['user_id'];
                    $arr['title'] = "购买" . $order['title'] . "分佣";
                    $arr['pid'] = $piduser['id'];
                    $arr['income'] = $divider;
                    $arr['create_time'] = time();
                    $arr['order_id'] = $order['id'];

                    Db::name('user_team')->insert($arr);
                }

                Db::commit();
                return true;
            } catch (\Exception $e) {
                Db::rollback();
                Log::write('预约下单支付回调逻辑结束' . $e->getMessage());
            }
            return true;
        }
        });
        return $response->send();
    }


    public function createDay($type, $num)
    {
        $start = date('Y-m-d H:i:s');
        switch ($type) {
            case 1:
                $date = date('Y-m-d H:i:s', strtotime($start . '+' . $num . ' month'));
                break;
            case 2:
                $date = date('Y-m-d H:i:s', strtotime($start . '+' . ($num * 3) . ' month'));
                break;
            case 3:
                $date = date('Y-m-d H:i:s', strtotime($start . '+' . $num . ' year'));
                break;
            case 4:
                $date = date('Y-m-d H:i:s', strtotime($start . '+' . 99 . ' year'));
                break;
        }
        return strtotime($date);
    }


    /**
     * 预约下单回调.
     */
    public function rechargeSavingNotify()
    {
        $config = Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);

//        $message = array(
//            'appid' => 'wxf436cffbaba49829',
//            'bank_type' => 'OTHERS',
//            'cash_fee' => '1',
//            'fee_type' => 'CNY',
//            'is_subscribe' => 'N',
//            'mch_id' => '1626297451',
//            'nonce_str' => '66b043a7177fd',
//            'openid' => 'obaxI5d8vIWZPbNAJ5QGQED3rTqo',
//            'out_trade_no' => 'XD18738610106855',
//            'result_code' => 'SUCCESS',
//            'return_code' => 'SUCCESS',
//            'sign' => 'ACBED99C27B0D319EE5AB54381807ADC',
//            'time_end' => '20240805111451',
//            'total_fee' => '1',
//            'trade_type' => 'JSAPI',
//            'transaction_id' => '4200002345202408058764788880',
//        );
        $response = $app->handlePaidNotify(function ($message, $fail) use ($app) {
            if ($message['return_code'] == "SUCCESS" && $message["result_code"] == "SUCCESS") {
                $out_trade_no = $message['out_trade_no'];//订单号
                $order = Db::name('saving_order')->where(['out_trade_no' => $out_trade_no, 'status' => 0])->find();
                //如果该订单未找到或已支付,返回true
                if (!$order) {
                    return true;
                }
                //更改订单状态
                $upda_data = [
                    'status' => 2,
                    'transaction_id' => $message['transaction_id'], //微信支付订单号
                    'pay_time' => time(), //支付完成时间
                    'pay_money' => $message['total_fee'] / 100, //支付金额
                ];
                try {
                    $user = Db::name('user')->where(['id' => $order['user_id']])->find();
                    Db::startTrans();
                    Db::name('saving_order')->where('out_trade_no', $out_trade_no)->update($upda_data);
                    //执行增加金额

                    $amount = $order['pay_money'] + $order['send_money'] + $user['wallet'];
                    Db::name('user')->where(['id' => $order['user_id']])->update(
                        ['wallet' => $amount, 'updatetime' => time()]
                    );
                    //添加记录
                    $userBill['user_id'] = $order['user_id'];
                    $userBill['title'] = '充值储蓄卡';
                    $userBill['type'] = 1;
                    $userBill['amount'] = $order['pay_money'];
                    (new UserBill())->addUserBill($userBill);

                    $user = (new \app\api\model\User())->where(['id' => $order['user_id']])->find();
                    if($user['is_vip'] == 0 && $order['pay_money'] >= 300){
                        (new \app\api\model\User())->where(['id' => $order['user_id']])->update(['is_vip' => 1]);
                    }

                    //执行分佣
                    $piduser = Db::name('user')->where(['id' => $user['pid']])->find();
                    if ($piduser) {
                        $config = (new \app\common\model\Config())->where(['id' => 45])->find();
                        $divider = number_format($order['pay_money'] * $config['value'] / 100, 2);
                        $team_money = $piduser['team_money'] + $divider;
                        $team_total_money = $piduser['team_total_money'] + $divider;
                        Db::name('user')->where(['id' => $user['pid']])->update(
                            ['team_money' => $team_money, 'team_total_money' => $team_total_money]
                        );
                        //添加明细
                        $arr['user_id'] = $order['user_id'];
                        $arr['title'] = "充值储蓄卡分佣";
                        $arr['pid'] = $piduser['id'];
                        $arr['income'] = $divider;
                        $arr['create_time'] = time();
                        $arr['order_id'] = $order['id'];
                        Db::name('user_team')->insert($arr);
                    }

                    Db::commit();
                } catch (\Exception $e) {

                    Db::rollback();
                    Log::write('预约下单支付回调逻辑结束' . $e->getMessage());
                }
                return true;
            }
        });
        return $response->send();
    }

}
